//
//  CDWallpaperViewController.m
//  CollectToDesktop
//
//  Created by 王启颖 on 2020/10/19.
//  Copyright © 2020 godbe. All rights reserved.
//

#import "CDWallpaperViewController.h"
#import <Photos/Photos.h>
@interface CDWallpaperViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *bgImg;

@end

@implementation CDWallpaperViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"壁纸";

    [self.bgImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.dic[@"wallpaperUrl"]]] placeholderImage:[UIImage imageNamed:@"1234"]];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"返 回(2)"] forState:UIControlStateNormal];
    [button setFrame:CGRectMake(0, 0, 60, 40)];
    button.contentEdgeInsets = UIEdgeInsetsMake(0, -20,0, 0);
    [button addTarget:self action:@selector(navigationItemBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem =  item;
}

-(void)navigationItemBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)saveClick:(id)sender {
    [self saveImageClick];
}
- (void) saveImageClick {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusDenied) {
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"提示"
                                                                    message:@"请到【设置-隐私-照片】打开访问开关"
                                                             preferredStyle:UIAlertControllerStyleAlert];
        
        // 2.创建并添加按钮
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"OK Action");
        }];
        [vc addAction:okAction];           // A

        [self presentViewController:vc animated:YES completion:nil];
        
        
    } else if (status == PHAuthorizationStatusRestricted) {
        NSLog(@"无法访问相册");
    } else {
       
        UIImage *saveImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.dic[@"wallpaperUrl"]]]];
        [self saveImageToPhotos:saveImage];
    }
}

- (void)saveImageToPhotos:(UIImage*)savedImage {
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo {
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    [SVProgressHUD showImage:NULL_IMAGE status:msg];
    [self.navigationController popViewControllerAnimated:YES];
}
@end
